package com.lzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzy.base.BaseInfoProperties;
import com.lzy.mapper.ChatMessageMapper;
import com.lzy.pojo.ChatMessage;
import com.lzy.pojo.netty.ChatMsg;
import com.lzy.service.ChatMessageService;
import com.lzy.utils.PagedGridResult;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lzy
 * @since 2025-08-26
 */
@Service
public class ChatMessageServiceImpl extends BaseInfoProperties implements ChatMessageService {

    @Resource
    private ChatMessageMapper chatMessageMapper;

    @Transactional
    @Override
    public void saveMsg(ChatMsg chatMsg) {

        ChatMessage chatMessage = new ChatMessage();
        BeanUtils.copyProperties(chatMsg, chatMessage);

        // 手动设置聊天信息的主键id
        chatMessage.setId(chatMsg.getMsgId());

        chatMessageMapper.insert(chatMessage);

        String receiverId = chatMsg.getReceiverId();
        String senderId = chatMsg.getSenderId();

        // 通过redis累加信息接受者的对应的未读消息数
        redis.incrementHash(CHAT_MSG_LIST + ":" + receiverId,senderId,1);
    }

    @Override
    public PagedGridResult queryChatMsgList(String senderId, String receiverId, Integer page, Integer pageSize) {

        Page<ChatMessage> pageInfo = new Page<>(page, pageSize);

        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<ChatMessage>()
                .or(qw -> qw.eq("sender_id", senderId)
                            .eq("receiver_id", receiverId))
                .or(qw -> qw.eq("sender_id", receiverId)
                            .eq("receiver_id", senderId))
                .orderByDesc("chat_time");
        chatMessageMapper.selectPage(pageInfo, queryWrapper);

        List<ChatMessage> list = pageInfo.getRecords();
        // 获得聊天的最新数据应该处于聊天框的最下方，因此进行排序操作
        List<ChatMessage> msglist = list.stream().sorted(
                                       Comparator.comparing(ChatMessage::getChatTime)
                                        ).collect(Collectors.toList());
        pageInfo.setRecords(msglist);
        return setterPagedGridPlus(pageInfo);
    }

    @Transactional
    @Override
    public void updateMsgSignRead(String msgId) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setId(msgId);
        chatMessage.setIsRead(true);
        chatMessageMapper.updateById(chatMessage);
    }
}
